<?php

class Access_Log_Model extends Auto_Modeler_ORM
{
	protected $db = 'access_log';

	protected $table_name = 'access_log';

	protected $data = array('id' => NULL,
	                        'date' => 0,
	                        'file' => '',
	                        'referrer' => '',
	                        'method' => '',
	                        'protocol' => '',
	                        'language' => '',
	                        'user_agent' => '',
	                        'remote_addr' => '',
	                        'remote_host' => '',
	                        'session_id' => '');

	protected $rules = array('date' => array('required', 'numeric'),
	                         'file' => array('required', 'standard_text'));


	// Generates a 2-d array of visitors vs time
	public function visitors($start_date, $end_date, $increment = 86400)
	{
		$return = array();

		foreach (Auto_Modeler_ORM::factory('access_log')->fetch_where(array('date >=' => $start_date, 'date <' => $end_date)) as $access)
		{
			// Find where the row should go in the return array
			$return[strtotime(date('m/d/Y', $access->date))][] = $access;
		}

		// Make sure every date is filled in
		for ($date = $start_date; $date <= $end_date; $date+=$increment)
		{
			if ( ! isset($return[strtotime(date('m/d/Y', $date))]))
				$return[strtotime(date('m/d/Y', $date))] = array();
		}

		ksort($return);

		return $return;
	}

	public function unique_visitors($start_date, $end_date, $increment = 86400)
	{
		$return = array();
		$visits = array();

		foreach (Auto_Modeler_ORM::factory('access_log')->fetch_where(array('date >=' => $start_date, 'date <' => $end_date)) as $access)
		{
			// Find where the row should go in the return array
			if ( ! in_array($access->session_id, $visits))
			{
				$return[strtotime(date('m/d/Y', $access->date))][] = $access;
				$visits[] = $access->session_id;
			}
		}

		// Make sure every date is filled in
		for ($date = $start_date; $date <= $end_date; $date+=$increment)
		{
			if ( ! isset($return[strtotime(date('m/d/Y', $date))]))
				$return[strtotime(date('m/d/Y', $date))] = array();
		}

		ksort($return);

		return $return;
	}
}